package com.gamewithpurpose.dbinterface;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.gamewithpurpose.dbinterface.POJO.Answer;

/*
 * AnswerDAO contains all interfaces to manage data in the Answer table. 
 */
public class AnswerDAO {
	/* 
	 * Add a new entry
	 */
	public static Integer addAnswer(int userId, int phraseId, String answer) {
		Session session = DBFactory.getSessionFactory().openSession();
		Transaction tx = null;
		Integer id = null;
		
		try {
			tx = session.beginTransaction();
			Answer pojo = new Answer(userId, phraseId, answer);
			id = (Integer) session.save(pojo);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return id;
	}

	/*
	 * Get all answers
	 */
	public static List<Answer> list() {
		Session session = DBFactory.getSessionFactory().openSession();
		Transaction tx = null;
		List<Answer> answers = null;
		
		try {
			tx = session.beginTransaction();
			answers = session.createQuery("FROM Answer").list();
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		
		return answers;
	}
	
	/*
	 * Delete an answer with id
	 */
	public static void delete(int id) {
		Session session = DBFactory.getSessionFactory().openSession();
		Transaction tx = null;
		
		try {
			tx = session.beginTransaction();
			Answer pojo = (Answer) session.get(Answer.class, id);
			session.delete(pojo);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
	
	/*
	 * Delete all answers and return the number of deleted entries.
	 */
	public static int deleteAll() {
		Session session = DBFactory.getSessionFactory().openSession();
		Transaction tx = null;
		int res = 0;
		
		try {
			tx = session.beginTransaction();
			res = session.createQuery("delete FROM Answer").executeUpdate();
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		
		return res;
	}
}
